var Qtool = Qtool || {};
Qtool.cookie = function()
{//{{{
    var GetCookieVal = function(offset)
    {
        var endstr = document.cookie.indexOf (";", offset);
        if (endstr == -1)
            endstr = document.cookie.length;
        return unescape(document.cookie.substring(offset, endstr));
    };
    var getCookie = function (name)
    {//{{{
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen)
        {
            var j = i + alen;
            if (document.cookie.substring(i, j) == arg)
                return GetCookieVal (j);
            i = document.cookie.indexOf(" ", i) + 1;
            if (i == 0) break;
        }
        return null;
    }; //}}}
    var setCookie = function (argv)
    {
        var expdate = new Date();
        var argc = argv.length;
        var name = argv[0];
        var value = argv[1];
        var expires = (argc > 2) ? argv[2] : null;
        var path = (argc > 3) ? argv[3] : null;
        var domain = (argc > 4) ? argv[4] : null;
        var secure = (argc > 5) ? argv[5] : false;
        if(expires!=null) expdate.setTime(expdate.getTime() + ( expires*24*60*60*1000 ));
        document.cookie = name + "=" + escape (value) +((expires == null) ? "" : ("; expires="+ expdate.toGMTString()))
            +((path == null) ? "" : ("; path=" + path)) +((domain == null) ? "" : ("; domain=" + domain))
            +((secure == true) ? "; secure" : "");
    }; 
    if(arguments.length > 1)
    {
        return setCookie(arguments);
    }else{
        return getCookie(arguments[0]);
    }
}//}}}
Qtool.suggest = function(data)
{//{{{
    if(typeof $.extend != 'function') return;
    var suggest = {
        //{{{
        quantifier:'个团购',
        offset:0,
        url:'',
        inputid:'',
        inputBox:null,
        defkeyword:'',
        history_keywords:[],
        history_result:[],
        noResultKeywords:[],
        curKeyword:'',
        curLiLen:0,
        curListIndex:-1,
        isTriggerBlur : true,
        noEventKeycode:[9,13,16,17,18,19,20,33,34,35,36,37,39,41,42,43,45,47],
        assemblyList:function()
        {
            var obj = this.inputBox,detail = this.offset;
            var list_left = obj.offset().left-detail, list_top = obj.offset().top + obj.outerHeight(),list_width = obj.innerWidth()+detail;
            var style =' .suggest_content{display:none;position:absolute;z-index:200;left:'+list_left+'px;top:'+list_top+'px;width:'+(list_width)+'px;border:1px solid #ccc;border-top:0 none;background:#fff;} .suggest_content li{height:24px;padding:0 5px;line-height:24px;} .suggest_content .current{background:#ffe9be;cursor:pointer;} .suggest_key{float:left;} .suggest_result{float:right;} .suggest_result strong{color:#f60;font-weight:normal;}';
            var listHmtl = ' <div class="suggest_content" id="suggest_content"> <ul>  </ul> </div>';
            $('head').append('<style>'+style+'</style>');
            $('body').append(listHmtl);
        },
        hideList:function()
        {
            var list = $('#suggest_content');
            this.curLiLen = 0;
            list.hide();
            list.find('ul').html('');
        },
        isUsefulKW:function()
        {
            var kw = this.curKeyword,nr = this.noResultKeywords;
            for(var i=0,len =nr.length;i<len;i++)
            {
                if(kw.indexOf(nr[i]) > -1)
                    return false;
            }
            return true;
        },
        boxEventHandle:function()
        {//{{{
            var list = $('#suggest_content');
            var obj = this.inputBox;
            var topThis = this;
            $(window).resize(function(){
                list.css('left',obj.offset().left-topThis.offset);
            })
            list.find('li').live('mouseover',function(){
                list.find('li').removeClass('current');
                $(this).addClass('current');
                topThis.isTriggerBlur = false;
            }).live('mouseout',function(){
                topThis.curListIndex = -1;
                list.find('li').removeClass('current');
                topThis.isTriggerBlur = true;
            });
            obj.blur(function(){
                if(!topThis.isTriggerBlur){ 
                    var val = list.find('.current').find('.suggest_key').text();
                    obj.val(val);
                    obj.parents('form').submit();
                }
                topThis.hideList();
            })
            obj.keyup(function(e){
                var keycode = e.keyCode;
                if(keycode > 111 && keycode < 138) return;
                if($.inArray(keycode,topThis.noEventKeycode) > -1) return;
                if(keycode == 27){
                    topThis.hideList();
                    return;
                }
                var liLen = topThis.curLiLen;
                if(liLen) {
                    var lis = list.find('li');
                    lis.removeClass('current');
                    var curIndex = topThis.curListIndex;
                    if(keycode == 40){
                        curIndex++;
                        if( curIndex == liLen){
                            this.value = topThis.curKeyword;
                            topThis.curListIndex = -1;
                            return;
                        }
                        var cur = lis.eq(curIndex);
                        cur.mouseover();
                        this.value = cur.find('.suggest_key').text();
                        topThis.curListIndex = curIndex;
                        return;
                    }
                    if(keycode == 38) {
                        curIndex--;
                        if(curIndex == -2) curIndex = liLen-1;
                        if( curIndex == -1){
                            this.value = topThis.curKeyword;
                            topThis.curListIndex = -1;
                            return;
                        }
                        var cur = lis.eq(curIndex);
                        cur.mouseover();
                        this.value = cur.find('.suggest_key').text();
                        topThis.curListIndex = curIndex;
                        return;
                    }
                }
                var keyword = $.trim(this.value);
                if(keyword && keyword != topThis.defkeyword) {
                    topThis.curKeyword = keyword;
                    topThis.curListIndex = -1;
                    if(!topThis.isUsefulKW())
                    {
                        topThis.hideList();
                        return;
                    }
                    var index = $.inArray(keyword,topThis.history_keywords);
                    if( index > -1){
                        topThis.appendToList(topThis.history_result[index]);
                    }else{
                        $.getScript(topThis.url+encodeURIComponent(keyword),function(tempdata){
                            var data;
                            try{
                                data = eval("("+tempdata+")");
                            }catch(e){
                            }
                            if(data) {
                                topThis.appendToList(data);
                                topThis.history_keywords.push(keyword);
                                topThis.history_result.push(data);
                                if(!data.length) topThis.noResultKeywords.push(keyword);
                            }
                        });
                    }
                }else{
                    topThis.hideList();
                }
            })
        },//}}}
        appendToList:function(data)
        {
            var data = data ? data : [];
            var list = $('#suggest_content');
            var len  = data.length 
            if(len > 0){
                var html = [];
                for(var i=0;i<len;i++)
                {
                    var temp = data[i];
                    html.push('<li><span class="suggest_key">'+temp[0]+'</span><span  class="suggest_result">约<strong>'+temp[1]+'</strong>'+this.quantifier+'</span></li> ');
                }
                this.curLiLen = len;
                list.find('ul').html(html.join(''));
                list.show();
            }else{
                this.hideList();
            }
        },
        main:function()
        {
            var obj = $(this.inputid);
            var topThis = this;
            if(!obj[0] || !this.url) return;
            this.inputBox = obj;
            if(!this.defkeyword) this.defkeyword =  obj.val();
            obj.attr('autocomplete','off');
            obj.one('focus',function(){
                topThis.assemblyList();
                topThis.boxEventHandle();
            });
        }
        //}}}
    }
    $.extend(suggest,data);
    $(function(){
        try{
            suggest.main();
        }catch(e){
        }
    })
}//}}}
Qtool.lazyLoadImg = function(data)
{//{{{
    var options = {
        imgs:null,
        replaceName:'_src',
        imgHeight:300,
        pre:200,
        nopic:'http://p6.qhimg.com/t0192160a7fed21bf8c.png'
    }
    $.extend(options,data);
    if(!options.imgs) return;
    var timer,imgh = options.imgHeight,preHeight = options.pre,replaceName = options.replaceName;
    var wWidth = $(window).width(),wHeigh = $(window).height();
    var imgs = options.imgs.find('img'), imgN = imgs.length, countImg = 0, topThis = this;
    $(window).scroll(function(){
        if(timer) clearTimeout(timer);
        if(countImg == imgN) return;   
        timer = setTimeout(function(){
            var sTop = $(window).scrollTop();
            imgs.each(function(){
                var tTop = $(this).offset().top;
                var src = $(this).attr('src');
                if( (!src || src == options.nopic) && tTop > sTop - imgh && tTop < sTop + wHeigh + preHeight ) {   
                    countImg++;
                    $(this).attr('src',$(this).attr(replaceName));
                }   
            })  
        },50)
    }); 
    if(!$(window).scrollTop()){
        $(window).scroll();
    }   
}//}}}
Qtool.slidebar = function(data)
{//{{{
    if(typeof $.extend != 'function') return;
    var slidebar = {
        pageWidth:0,
        direction:'right',
        selector:'',
        content:'',
        main:function()
        {
            $.extend(slidebar,data);
            if(this.content) $('body').append(this.content);
            var selector = $(this.selector);
            if(!selector[0]) return;
            var isIE6 = !window.XMLHttpRequest;
            var position = isIE6 ? 'absolute' : 'fixed';
            var topH = $(window).height()/2;
            var offsetVal = - (this.pageWidth/2+selector.width());
            var css = {'position':position,'top':topH};
            var direction = this.direction;
            css[direction] = '50%';
            css['margin-'+direction] = offsetVal;
            selector.css(css);
            if(!this.content && !selector.parent().is('body')) $('body').append(selector);
            selector.show();
            if(isIE6)
            {
                $(window).scroll(function(){
                    selector.css('top',$(window).scrollTop()+topH);
                })
            }
        }
    }
    $(function(){
        slidebar.main();
    });
}//}}}
Qtool.goTop = function(pageWidth,value,bottom,imgsrc) 
{   //{{{
    var pageWidth = pageWidth,value = value ? value : 0,bottom = bottom ? bottom : 80;
    var imgsrc = imgsrc ? imgsrc : 'http://p8.qhimg.com/t01fbf458a6a0179516.gif';
    var goTop = {
        imgInfo:[],
        assemblyHtml:function()
        {
            var w = this.topImgInfo[0],h = this.topImgInfo[1];
            if(!pageWidth) pageWidth = $('body').find('div').eq(0).width();
            var style = '.Q_gotop{ background: url("'+imgsrc+'") no-repeat scroll 0 0 transparent; \
                cursor: pointer; display: none; height: '+h+'px; right:50%; position: fixed;_position:absolute; width: '+w+'px; z-index: 99; \
                    margin-right:'+(-(pageWidth/2+w+1))+'px;}';
            $('head').append('<style>'+style+'</style>');
            $('body').append('<div id="Q_gotop" class="Q_gotop"></div>');
        },
        handleEvent:function()
        {
            var hh = this.topImgInfo[1]+bottom;
            var Q_gotop = $('#Q_gotop');
            Q_gotop.click(function(){
                $(window).scrollTop(0);
            });
            $(window).scroll(function(){
                var wh = $(this).height();
                var sTop = $(this).scrollTop();
                if(sTop > value) {
                    if(!window.XMLHttpRequest){
                        Q_gotop.css('top',wh-hh+sTop);
                    }else{
                        Q_gotop.css('bottom',bottom);
                    }
                    Q_gotop.show();
                }else{
                    Q_gotop.hide();
                }

            })
        },
        main:function()
        {
            var topThis = this;
            var topImg = new Image();
            topImg.onerror = topImg.onload = function(){
                topThis.topImgInfo = [topImg.width,topImg.height];
                topThis.assemblyHtml();
                topThis.handleEvent();
            }
            topImg.src = imgsrc;
            if(topImg.complete)
            {
                topThis.topImgInfo = [topImg.width,topImg.height];
                topThis.assemblyHtml();
                topThis.handleEvent();
                return;
            }

        }   
    }   
    $(function(){
        goTop.main();
    });
}//}}}
